package com.example.bigupload.controller;

import com.example.bigupload.manager.MinioManagerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.*;

@RestController
public class FileDownloadController {

    @Autowired
    private MinioManagerService minioManagerService;

    @GetMapping("/download-zip")
    public void downloadZip(HttpServletResponse response) {

        String zipFileName = "compressed_files.zip";

        try {
            // 1. 下载文件到临时目录
            File tempDir = minioManagerService.downloadAndZipFiles();

            // 2. 将临时目录压缩为 ZIP 文件
            File zipFile = minioManagerService.zipDirectory(tempDir);

            // 3. 上传 ZIP 文件到 MinIO
            minioManagerService.uploadFileToMinio(zipFile, zipFileName);

            // 4. 将 ZIP 文件返回给前端
//            response.setContentType("application/zip");
//            response.setHeader("Content-Disposition", "attachment; filename=" + zipFileName);
//            try (InputStream inputStream = new FileInputStream(zipFile);
//                 OutputStream outputStream = response.getOutputStream()) {
//                byte[] buffer = new byte[8192];
//                int bytesRead;
//                while ((bytesRead = inputStream.read(buffer)) != -1) {
//                    outputStream.write(buffer, 0, bytesRead);
//                }
//                outputStream.flush();
//            }

            // 5. 删除临时目录和 ZIP 文件
            zipFile.delete();
            minioManagerService.deleteDirectory(tempDir);

        } catch (Exception e) {
            e.printStackTrace();
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }
}
